package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("1003")
@SuppressWarnings({"all"})
public class VipStrategyImpl implements ItemTypeStrategy {

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserVipServiceMapper userVipServiceMapper;
    @Override
    public int savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //定义一个计数器
        int count = 0;
        //获取vip服务配置
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(userPaidRecordVo.getItemIdList().get(0));
        //获取当前用户vip情况
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        if (userInfo.getIsVip()==0 || userInfo.getVipExpireTime().before(new Date())){
            //订阅vip
            userInfo.setIsVip(1);
            userInfo.setVipExpireTime(LocalDateTime.now().plusMonths(vipServiceConfig.getServiceMonth()).toDate());
        }else {
            //vip续期
            userInfo.setVipExpireTime(new LocalDateTime(userInfo.getVipExpireTime()).plusMonths(vipServiceConfig.getServiceMonth()).toDate());
        }
        count += userInfoMapper.updateById(userInfo);
        //新增user_vip_service表
        UserVipService userVipService = new UserVipService();
        userVipService.setUserId(userPaidRecordVo.getUserId());
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setExpireTime(userInfo.getVipExpireTime());
        userVipService.setStartTime(new Date());
        count += userVipServiceMapper.insert(userVipService);
        return count;
    }
}
